package com.fz.study.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fz.study.project.entity.RedisData;
import com.fz.study.project.entity.Result;
import com.fz.study.project.entity.Shop;
import com.fz.study.project.exception.BizException;
import com.fz.study.project.mapper.TbShopMapper;
import com.fz.study.project.service.ITbShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fz.study.project.utils.CacheClientUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.fz.study.project.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-02-26
 */
@RequiredArgsConstructor
@Service
public class ShopServiceImpl extends ServiceImpl<TbShopMapper, Shop> implements ITbShopService {

    private final StringRedisTemplate stringRedisTemplate;
    private final CacheClientUtils cacheClientUtils;

    @Override
    public Object queryById(Long id) {
//        解决缓存穿透
//        Shop shop = cacheClientUtils.queryWithPassThrough(CACHE_SHOP_KEY,id, Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
//        互斥锁解决缓存击穿
//        Shop shop = queryWithMutex(id);
        Shop shop = cacheClientUtils.queryWithMutex(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        逻辑删除解决缓存击穿
//        Shop shop = cacheClientUtils.queryWithLogicalExpire(CACHE_SHOP_KEY,id, Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
        if (shop == null) {
            BizException.throwBizException("商户不存在！");
        }
        return Result.success(shop);
    }
    @Override
    @Transactional
    public Object updateWithId(Shop shop) {
        if (Objects.isNull(shop.getId())) {
            BizException.throwBizException("更新数据id不能为空！");
        }
//        更新数据库
        updateById(shop);
//        删除redis缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.success("数据更新成功！");
    }
}
